3 * Created on Dec 01, 2007
5 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
28 class ApiParse
extends ApiBase
{
30 /** @var string $section */
31 private $section = null;
33 /** @var Content $content */
34 private $content = null;
36 /** @var Content $pstContent */
37 private $pstContent = null;
39 public function execute() {
40 // The data is hot but user-dependent, like page views, so we set vary cookies
41 $this->getMain()->setCacheMode( 'anon-public-user-private' );
44 $params = $this->extractRequestParams();
45 $text = $params['text'];
46 $title = $params['title'];
47 if ( $title === null ) {
48 $titleProvided = false;
49 // A title is needed for parsing, so arbitrarily choose one
52 $titleProvided = true;
55 $page = $params['page'];
56 $pageid = $params['pageid'];
57 $oldid = $params['oldid'];
59 $model = $params['contentmodel'];
60 $format = $params['contentformat'];
62 if ( !is_null( $page ) && ( !is_null( $text ) ||
$titleProvided ) ) {
64 'The page parameter cannot be used together with the text and title parameters',
69 $prop = array_flip( $params['prop'] );
71 if ( isset( $params['section'] ) ) {
72 $this->section
= $params['section'];
73 if ( !preg_match( '/^((T-)?\d+|new)$/', $this->section
) ) {
74 $this->dieUsage( "The section parameter must be a valid section id or 'new'", "invalidsection" );
77 $this->section
= false;
80 // The parser needs $wgTitle to be set, apparently the
81 // $title parameter in Parser::parse isn't enough *sigh*
82 // TODO: Does this still need $wgTitle?
83 global $wgParser, $wgTitle;
88 $result = $this->getResult();
90 if ( !is_null( $oldid ) ||
!is_null( $pageid ) ||
!is_null( $page ) ) {
91 if ( $this->section
=== 'new' ) {
92 $this->dieUsage( 'section=new cannot be combined with oldid, pageid or page parameters. Please use text', 'params' );
94 if ( !is_null( $oldid ) ) {
95 // Don't use the parser cache
96 $rev = Revision
::newFromId( $oldid );
98 $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
100 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
101 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
104 $titleObj = $rev->getTitle();
105 $wgTitle = $titleObj;
106 $pageObj = WikiPage
::factory( $titleObj );
107 $popts = $this->makeParserOptions( $pageObj, $params );
109 // If for some reason the "oldid" is actually the current revision, it may be cached
110 if ( $rev->isCurrent() ) {
111 // May get from/save to parser cache
112 $p_result = $this->getParsedContent( $pageObj, $popts,
113 $pageid, isset( $prop['wikitext'] ) );
114 } else { // This is an old revision, so get the text differently
115 $this->content
= $rev->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
117 if ( $this->section
!== false ) {
118 $this->content
= $this->getSectionContent( $this->content
, 'r' . $rev->getId() );
121 // Should we save old revision parses to the parser cache?
122 $p_result = $this->content
->getParserOutput( $titleObj, $rev->getId(), $popts );
124 } else { // Not $oldid, but $pageid or $page
125 if ( $params['redirects'] ) {
130 if ( !is_null( $pageid ) ) {
131 $reqParams['pageids'] = $pageid;
133 $reqParams['titles'] = $page;
135 $req = new FauxRequest( $reqParams );
136 $main = new ApiMain( $req );
138 $data = $main->getResultData();
139 $redirValues = isset( $data['query']['redirects'] )
140 ?
$data['query']['redirects']
143 foreach ( (array)$redirValues as $r ) {
146 $pageParams = array( 'title' => $to );
147 } elseif ( !is_null( $pageid ) ) {
148 $pageParams = array( 'pageid' => $pageid );
150 $pageParams = array( 'title' => $page );
153 $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
154 $titleObj = $pageObj->getTitle();
155 if ( !$titleObj ||
!$titleObj->exists() ) {
156 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
158 $wgTitle = $titleObj;
160 if ( isset( $prop['revid'] ) ) {
161 $oldid = $pageObj->getLatest();
164 $popts = $this->makeParserOptions( $pageObj, $params );
166 // Potentially cached
167 $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
168 isset( $prop['wikitext'] ) );
170 } else { // Not $oldid, $pageid, $page. Hence based on $text
171 $titleObj = Title
::newFromText( $title );
172 if ( !$titleObj ||
$titleObj->isExternal() ) {
173 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
175 $wgTitle = $titleObj;
176 if ( $titleObj->canExist() ) {
177 $pageObj = WikiPage
::factory( $titleObj );
179 // Do like MediaWiki::initializeArticle()
180 $article = Article
::newFromTitle( $titleObj, $this->getContext() );
181 $pageObj = $article->getPage();
184 $popts = $this->makeParserOptions( $pageObj, $params );
185 $textProvided = !is_null( $text );
187 if ( !$textProvided ) {
188 if ( $titleProvided && ( $prop ||
$params['generatexml'] ) ) {
190 "'title' used without 'text', and parsed page properties were requested " .
191 "(did you mean to use 'page' instead of 'title'?)"
194 // Prevent warning from ContentHandler::makeContent()
198 // If we are parsing text, do not use the content model of the default
199 // API title, but default to wikitext to keep BC.
200 if ( $textProvided && !$titleProvided && is_null( $model ) ) {
201 $model = CONTENT_MODEL_WIKITEXT
;
202 $this->setWarning( "No 'title' or 'contentmodel' was given, assuming $model." );
206 $this->content
= ContentHandler
::makeContent( $text, $titleObj, $model, $format );
207 } catch ( MWContentSerializationException
$ex ) {
208 $this->dieUsage( $ex->getMessage(), 'parseerror' );
211 if ( $this->section
!== false ) {
212 if ( $this->section
=== 'new' ) {
213 // Insert the section title above the content.
214 if ( !is_null( $params['sectiontitle'] ) && $params['sectiontitle'] !== '' ) {
215 $this->content
= $this->content
->addSectionHeader( $params['sectiontitle'] );
218 $this->content
= $this->getSectionContent( $this->content
, $titleObj->getPrefixedText() );
222 if ( $params['pst'] ||
$params['onlypst'] ) {
223 $this->pstContent
= $this->content
->preSaveTransform( $titleObj, $this->getUser(), $popts );
225 if ( $params['onlypst'] ) {
226 // Build a result and bail out
227 $result_array = array();
228 $result_array['text'] = array();
229 ApiResult
::setContent( $result_array['text'], $this->pstContent
->serialize( $format ) );
230 if ( isset( $prop['wikitext'] ) ) {
231 $result_array['wikitext'] = array();
232 ApiResult
::setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
234 if ( !is_null( $params['summary'] ) ||
235 ( !is_null( $params['sectiontitle'] ) && $this->section
=== 'new' )
237 $result_array['parsedsummary'] = array();
238 ApiResult
::setContent( $result_array['parsedsummary'], $this->formatSummary( $titleObj, $params ) );
241 $result->addValue( null, $this->getModuleName(), $result_array );
246 // Not cached (save or load)
247 if ( $params['pst'] ) {
248 $p_result = $this->pstContent
->getParserOutput( $titleObj, null, $popts );
250 $p_result = $this->content
->getParserOutput( $titleObj, null, $popts );
254 $result_array = array();
256 $result_array['title'] = $titleObj->getPrefixedText();
258 if ( !is_null( $oldid ) ) {
259 $result_array['revid'] = intval( $oldid );
262 if ( $params['redirects'] && !is_null( $redirValues ) ) {
263 $result_array['redirects'] = $redirValues;
266 if ( $params['disabletoc'] ) {
267 $p_result->setTOCEnabled( false );
270 if ( isset( $prop['text'] ) ) {
271 $result_array['text'] = array();
272 ApiResult
::setContent( $result_array['text'], $p_result->getText() );
275 if ( !is_null( $params['summary'] ) ||
276 ( !is_null( $params['sectiontitle'] ) && $this->section
=== 'new' )
278 $result_array['parsedsummary'] = array();
279 ApiResult
::setContent( $result_array['parsedsummary'], $this->formatSummary( $titleObj, $params ) );
282 if ( isset( $prop['langlinks'] ) ) {
283 $langlinks = $p_result->getLanguageLinks();
285 if ( $params['effectivelanglinks'] ) {
286 // Link flags are ignored for now, but may in the future be
287 // included in the result.
288 $linkFlags = array();
289 Hooks
::run( 'LanguageLinks', array( $titleObj, &$langlinks, &$linkFlags ) );
295 if ( isset( $prop['langlinks'] ) ) {
296 $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
298 if ( isset( $prop['categories'] ) ) {
299 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
301 if ( isset( $prop['categorieshtml'] ) ) {
302 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
303 $result_array['categorieshtml'] = array();
304 ApiResult
::setContent( $result_array['categorieshtml'], $categoriesHtml );
306 if ( isset( $prop['links'] ) ) {
307 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
309 if ( isset( $prop['templates'] ) ) {
310 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
312 if ( isset( $prop['images'] ) ) {
313 $result_array['images'] = array_keys( $p_result->getImages() );
315 if ( isset( $prop['externallinks'] ) ) {
316 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
318 if ( isset( $prop['sections'] ) ) {
319 $result_array['sections'] = $p_result->getSections();
322 if ( isset( $prop['displaytitle'] ) ) {
323 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
324 $p_result->getDisplayTitle() :
325 $titleObj->getPrefixedText();
328 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
329 $context = $this->getContext();
330 $context->setTitle( $titleObj );
331 $context->getOutput()->addParserOutputMetadata( $p_result );
333 if ( isset( $prop['headitems'] ) ) {
334 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
336 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
338 $scripts = array( $context->getOutput()->getHeadScripts() );
340 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
343 if ( isset( $prop['headhtml'] ) ) {
344 $result_array['headhtml'] = array();
345 ApiResult
::setContent(
346 $result_array['headhtml'],
347 $context->getOutput()->headElement( $context->getSkin() )
352 if ( isset( $prop['modules'] ) ) {
353 $result_array['modules'] = array_values( array_unique( $p_result->getModules() ) );
354 $result_array['modulescripts'] = array_values( array_unique( $p_result->getModuleScripts() ) );
355 $result_array['modulestyles'] = array_values( array_unique( $p_result->getModuleStyles() ) );
356 $result_array['modulemessages'] = array_values( array_unique( $p_result->getModuleMessages() ) );
359 if ( isset( $prop['indicators'] ) ) {
360 foreach ( $p_result->getIndicators() as $name => $content ) {
361 $indicator = array( 'name' => $name );
362 ApiResult
::setContent( $indicator, $content );
363 $result_array['indicators'][] = $indicator;
367 if ( isset( $prop['iwlinks'] ) ) {
368 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
371 if ( isset( $prop['wikitext'] ) ) {
372 $result_array['wikitext'] = array();
373 ApiResult
::setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
374 if ( !is_null( $this->pstContent
) ) {
375 $result_array['psttext'] = array();
376 ApiResult
::setContent( $result_array['psttext'], $this->pstContent
->serialize( $format ) );
379 if ( isset( $prop['properties'] ) ) {
380 $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
383 if ( isset( $prop['limitreportdata'] ) ) {
384 $result_array['limitreportdata'] =
385 $this->formatLimitReportData( $p_result->getLimitReportData() );
387 if ( isset( $prop['limitreporthtml'] ) ) {
388 $limitreportHtml = EditPage
::getPreviewLimitReport( $p_result );
389 $result_array['limitreporthtml'] = array();
390 ApiResult
::setContent( $result_array['limitreporthtml'], $limitreportHtml );
393 if ( $params['generatexml'] ) {
394 if ( $this->content
->getModel() != CONTENT_MODEL_WIKITEXT
) {
395 $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
398 $wgParser->startExternalParse( $titleObj, $popts, Parser
::OT_PREPROCESS
);
399 $dom = $wgParser->preprocessToDom( $this->content
->getNativeData() );
400 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
401 $xml = $dom->saveXML();
403 $xml = $dom->__toString();
405 $result_array['parsetree'] = array();
406 ApiResult
::setContent( $result_array['parsetree'], $xml );
409 $result_mapping = array(
412 'categories' => 'cl',
416 'externallinks' => 'el',
421 'indicators' => 'ind',
422 'modulescripts' => 'm',
423 'modulestyles' => 'm',
424 'modulemessages' => 'm',
425 'properties' => 'pp',
426 'limitreportdata' => 'lr',
428 $this->setIndexedTagNames( $result_array, $result_mapping );
429 $result->addValue( null, $this->getModuleName(), $result_array );
433 * Constructs a ParserOptions object
435 * @param WikiPage $pageObj
436 * @param array $params
438 * @return ParserOptions
440 protected function makeParserOptions( WikiPage
$pageObj, array $params ) {
442 $popts = $pageObj->makeParserOptions( $this->getContext() );
443 $popts->enableLimitReport( !$params['disablepp'] );
444 $popts->setIsPreview( $params['preview'] ||
$params['sectionpreview'] );
445 $popts->setIsSectionPreview( $params['sectionpreview'] );
446 $popts->setEditSection( !$params['disableeditsection'] );
452 * @param WikiPage $page
453 * @param ParserOptions $popts
455 * @param bool $getWikitext
456 * @return ParserOutput
458 private function getParsedContent( WikiPage
$page, $popts, $pageId = null, $getWikitext = false ) {
459 $this->content
= $page->getContent( Revision
::RAW
); //XXX: really raw?
461 if ( $this->section
!== false && $this->content
!== null ) {
462 $this->content
= $this->getSectionContent(
464 !is_null( $pageId ) ?
'page id ' . $pageId : $page->getTitle()->getPrefixedText()
467 // Not cached (save or load)
468 return $this->content
->getParserOutput( $page->getTitle(), null, $popts );
471 // Try the parser cache first
472 // getParserOutput will save to Parser cache if able
473 $pout = $page->getParserOutput( $popts );
475 $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
477 if ( $getWikitext ) {
478 $this->content
= $page->getContent( Revision
::RAW
);
485 * @param Content $content
486 * @param string $what Identifies the content in error messages, e.g. page title.
487 * @return Content|bool
489 private function getSectionContent( Content
$content, $what ) {
490 // Not cached (save or load)
491 $section = $content->getSection( $this->section
);
492 if ( $section === false ) {
493 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
495 if ( $section === null ) {
496 $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
504 * This mimicks the behavior of EditPage in formatting a summary
506 * @param Title $title of the page being parsed
507 * @param Array $params the API parameters of the request
508 * @return Content|bool
510 private function formatSummary( $title, $params ) {
512 $summary = !is_null( $params['summary'] ) ?
$params['summary'] : '';
513 $sectionTitle = !is_null( $params['sectiontitle'] ) ?
$params['sectiontitle'] : '';
515 if ( $this->section
=== 'new' && ( $sectionTitle === '' ||
$summary === '' ) ) {
516 if( $sectionTitle !== '' ) {
517 $summary = $params['sectiontitle'];
519 if ( $summary !== '' ) {
520 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
521 ->inContentLanguage()->text();
524 return Linker
::formatComment( $summary, $title, $this->section
=== 'new' );
527 private function formatLangLinks( $links ) {
529 foreach ( $links as $link ) {
531 $bits = explode( ':', $link, 2 );
532 $title = Title
::newFromText( $link );
534 $entry['lang'] = $bits[0];
536 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
537 // localised language name in 'uselang' language
538 $entry['langname'] = Language
::fetchLanguageName(
539 $title->getInterwiki(),
540 $this->getLanguage()->getCode()
543 // native language name
544 $entry['autonym'] = Language
::fetchLanguageName( $title->getInterwiki() );
546 ApiResult
::setContent( $entry, $bits[1] );
553 private function formatCategoryLinks( $links ) {
560 // Fetch hiddencat property
562 $lb->setArray( array( NS_CATEGORY
=> $links ) );
563 $db = $this->getDB();
564 $res = $db->select( array( 'page', 'page_props' ),
565 array( 'page_title', 'pp_propname' ),
566 $lb->constructSet( 'page', $db ),
569 array( 'page_props' => array(
570 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' )
573 $hiddencats = array();
574 foreach ( $res as $row ) {
575 $hiddencats[$row->page_title
] = isset( $row->pp_propname
);
578 foreach ( $links as $link => $sortkey ) {
580 $entry['sortkey'] = $sortkey;
581 ApiResult
::setContent( $entry, $link );
582 if ( !isset( $hiddencats[$link] ) ) {
583 $entry['missing'] = '';
584 } elseif ( $hiddencats[$link] ) {
585 $entry['hidden'] = '';
593 private function categoriesHtml( $categories ) {
594 $context = $this->getContext();
595 $context->getOutput()->addCategoryLinks( $categories );
597 return $context->getSkin()->getCategories();
600 private function formatLinks( $links ) {
602 foreach ( $links as $ns => $nslinks ) {
603 foreach ( $nslinks as $title => $id ) {
606 ApiResult
::setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
608 $entry['exists'] = '';
617 private function formatIWLinks( $iw ) {
619 foreach ( $iw as $prefix => $titles ) {
620 foreach ( array_keys( $titles ) as $title ) {
622 $entry['prefix'] = $prefix;
624 $title = Title
::newFromText( "{$prefix}:{$title}" );
626 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
629 ApiResult
::setContent( $entry, $title->getFullText() );
637 private function formatHeadItems( $headItems ) {
639 foreach ( $headItems as $tag => $content ) {
641 $entry['tag'] = $tag;
642 ApiResult
::setContent( $entry, $content );
649 private function formatProperties( $properties ) {
651 foreach ( $properties as $name => $value ) {
653 $entry['name'] = $name;
654 ApiResult
::setContent( $entry, $value );
661 private function formatCss( $css ) {
663 foreach ( $css as $file => $link ) {
665 $entry['file'] = $file;
666 ApiResult
::setContent( $entry, $link );
673 private function formatLimitReportData( $limitReportData ) {
675 $apiResult = $this->getResult();
677 foreach ( $limitReportData as $name => $value ) {
679 $entry['name'] = $name;
680 if ( !is_array( $value ) ) {
681 $value = array( $value );
683 $apiResult->setIndexedTagName( $value, 'param' );
684 $apiResult->setIndexedTagName_recursive( $value, 'param' );
685 $entry = array_merge( $entry, $value );
692 private function setIndexedTagNames( &$array, $mapping ) {
693 foreach ( $mapping as $key => $name ) {
694 if ( isset( $array[$key] ) ) {
695 $this->getResult()->setIndexedTagName( $array[$key], $name );
700 public function getAllowedParams() {
707 ApiBase
::PARAM_TYPE
=> 'integer',
709 'redirects' => false,
711 ApiBase
::PARAM_TYPE
=> 'integer',
714 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|' .
715 'images|externallinks|sections|revid|displaytitle|iwlinks|properties',
716 ApiBase
::PARAM_ISMULTI
=> true,
717 ApiBase
::PARAM_TYPE
=> array(
742 'effectivelanglinks' => false,
744 'sectiontitle' => array(
745 ApiBase
::PARAM_TYPE
=> 'string',
747 'disablepp' => false,
748 'disableeditsection' => false,
749 'generatexml' => array(
750 ApiBase
::PARAM_DFLT
=> false,
751 ApiBase
::PARAM_HELP_MSG
=> array(
752 'apihelp-parse-param-generatexml', CONTENT_MODEL_WIKITEXT
756 'sectionpreview' => false,
757 'disabletoc' => false,
758 'contentformat' => array(
759 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
761 'contentmodel' => array(
762 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
767 protected function getExamplesMessages() {
769 'action=parse&page=Project:Sandbox'
770 => 'apihelp-parse-example-page',
771 'action=parse&text={{Project:Sandbox}}&contentmodel=wikitext'
772 => 'apihelp-parse-example-text',
773 'action=parse&text={{PAGENAME}}&title=Test'
774 => 'apihelp-parse-example-texttitle',
775 'action=parse&summary=Some+[[link]]&prop='
776 => 'apihelp-parse-example-summary',
780 public function getHelpUrls() {
781 return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';